package com.chenjun.common.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.core.io.ClassPathResource;

/**
 * 读取配置文件的工具类，读取config.properties公共配置中的数据
 * 
 * @Title ConfigUtil
 * @author 李伟
 * @date 2015年6月24日 下午1:27:15
 */
public final class ConfigUtil {

	private static final Logger LOG = Logger.getLogger(ConfigUtil.class);

	public static final String CONFIG_FILE = "config.properties";

	/**
	 * 根据配置的文件获取配置参数值
	 * 
	 * @param filename :配置文件名称，默认是CONFIG_FILE
	 * @return Map<String,String>
	 */
	public static Map<String, String> getConfigInfo(String filename) {

		Map<String, String> configs = new HashMap<String, String>(0);
		Properties properties = getConfigProperties(filename);
		for (Iterator<?> its = properties.keySet().iterator(); its.hasNext();) {
			String key = (String) its.next();
			configs.put(key, properties.getProperty(key).trim());
		}

		return configs;
	}

	/**
	 * 根据配置的文件获取配置参数值
	 * 
	 * @param configName :配置文件名称，默认是CONFIG_FILE
	 * @return Properties
	 */
	public static Properties getConfigProperties(String configName) {
		if (StringUtils.isBlank(configName)) {
			configName = CONFIG_FILE;
		}

		ClassPathResource cp = new ClassPathResource(configName);
		Properties properties = new Properties();
		try {
			properties.load(cp.getInputStream());
		} catch (IOException e) {
			LOG.error("load " + configName + " error!", e);
			throw new RuntimeException("load " + configName + " error!");

		}
		return properties;
	}

	/**
	 * 获取指定Key的参数值
	 * 
	 * @param configName :默认config.properties
	 * @param key :配置项的key值
	 * @return String
	 */
	public static String getValue(String configName, String key) {
		Properties properties = getConfigProperties(null);
		return properties.getProperty(key, "");
	}

}
